package com.example.appalumaj;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class SendActivity extends Activity {

	String name = "";
	String carpeta = "";
	private boolean cuatro = false;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_send);
		
		if (Build.VERSION.SDK_INT > 10) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
			cuatro = true;
		}
		
		carpeta = getIntent().getExtras().getString("carpeta");
		
		Button neew = (Button) findViewById(R.id.button2);
		Button old = (Button) findViewById(R.id.button1);

		neew.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent, 1);
			}
		});

		old.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
				startActivityForResult(intent, 2);
			}
		});
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			// CAMARA
			
			Bitmap photo = (Bitmap) data.getExtras().get("data"); 
			ImageView iv = (ImageView) findViewById(R.id.imageView1);
			iv.setImageBitmap(photo);
			activaSubir();

		} else if (requestCode == 2) {
			// GALERIA
			if (data != null) {
				Uri selectedImage = data.getData();
				InputStream is;
				try {
					is = getContentResolver().openInputStream(selectedImage);
					BufferedInputStream bis = new BufferedInputStream(is);
					Bitmap bitmap = BitmapFactory.decodeStream(bis);
					ImageView iv = (ImageView) findViewById(R.id.imageView1);
					iv.setImageBitmap(bitmap);
					activaSubir();
				} catch (FileNotFoundException e) {
				}
			}

		}

	}
	
	
	public void activaSubir() {
		Button sub = (Button) findViewById(R.id.button3);
		Button gal = (Button) findViewById(R.id.button1);
		Button tom = (Button) findViewById(R.id.button2);
		
		gal.setVisibility(View.INVISIBLE);
		tom.setVisibility(View.INVISIBLE);
		
		sub.setVisibility(View.VISIBLE);
		sub.setOnClickListener(new OnClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				//SUBIR IMAGEN
				Toast.makeText(SendActivity.this, "Subiendo...", Toast.LENGTH_SHORT).show();
				
				if (cuatro) {
					new subeFoto().executeOnExecutor(
							AsyncTask.THREAD_POOL_EXECUTOR, "");
				} else {
					new subeFoto().execute("");
				}
			}
		});
	}
	
	
	private class subeFoto extends AsyncTask<String, Float, Integer> {

		File file;
		String nombre2;
		ByteArrayOutputStream bao;
		
		@Override
		protected Integer doInBackground(String... params) {
			try {
				ImageView img  = (ImageView)findViewById(R.id.imageView1);
				Bitmap bitmap = ((BitmapDrawable)img.getDrawable()).getBitmap();
				
				bao = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bao);
			} catch(Exception e){
				Log.i("error", "doInBackground");
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			byte [] ba = bao.toByteArray();
			
			String ba1 = Base64.encodeToString(ba, 1);

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

			nameValuePairs.add(new BasicNameValuePair("image",ba1));
			nameValuePairs.add(new BasicNameValuePair("carpeta",carpeta));
			
			try{

				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://www.alumaj.es/SubeFotos.php");
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				String respStr = EntityUtils.toString(response.getEntity());
	            
				Log.i("resultado", respStr);
				
	            finish();
	            Intent a = new Intent(SendActivity.this, MainActivity.class);
				startActivity(a);
				} catch (Exception e) {
					Log.i("error bitmap", e.getMessage());
				}
		}
		
	}
	
	private void toast(String tx) {
		Toast.makeText(SendActivity.this, tx, Toast.LENGTH_SHORT).show();
	}
}
